/*
 *所有关于cal_plan类的业务代码应在此处编写
*可使用repository.调用常用方法，获取EF/Dapper等信息
*如果需要事务请使用repository.DbContextBeginTransaction
*也可使用DBServerProvider.手动获取数据库相关信息
*用户信息、权限、角色等使用UserContext.Current操作
*cal_planService对增、删、改查、导入、导出、审核业务代码扩展参照ServiceFunFilter
*/
using VOL.Core.BaseProvider;
using VOL.Core.Extensions.AutofacManager;
using VOL.Entity.DomainModels;
using System.Linq;
using VOL.Core.Utilities;
using System.Linq.Expressions;
using VOL.Core.Extensions;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Http;
using MES.Calendar.IRepositories;
using VOL.Entity.DTO.Plan;
using System.Numerics;

namespace MES.Calendar.Services
{
    public partial class cal_planService
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly Ical_planRepository _repository;//访问数据库
        private readonly Ical_planteamRepository _plantemerepository;//访问数据库
        private readonly Ical_teamRepository _temerepository;//访问数据库
        private readonly Ical_planshiftRepository _planshiftrepository;//访问数据库
        private readonly Ical_teamshiftRepository _Cal_TeamShift;//访问数据库


        [ActivatorUtilitiesConstructor]
        public cal_planService(
            Ical_planRepository dbRepository,
            IHttpContextAccessor httpContextAccessor,
            Ical_planteamRepository plantemerepository,
            Ical_teamRepository temerepository,
            Ical_planshiftRepository planshiftrepository,
            Ical_teamshiftRepository Cal_TeamShift

            )
        : base(dbRepository)
        {
            _httpContextAccessor = httpContextAccessor;
            _repository = dbRepository;
            _plantemerepository = plantemerepository;
            _temerepository = temerepository;
            _planshiftrepository = planshiftrepository;
             _Cal_TeamShift = Cal_TeamShift;
            //多租户会用到这init代码，其他情况可以不用
            //base.Init(dbRepository);
        }
         public Addplanresultdto AddPlan(PlanDto plan)
        {

            Addplanresultdto cd=new Addplanresultdto();
            cd.count = 0;
            cd.teamnames = "";

            var cc = (from a in _repository.Find(x => 1 == 1)
                      join
                   b in _plantemerepository.Find(x => 1 == 1) on a.PlanId equals b.PlanId
                      select new
                      {
                          kstr = a.StartDate,
                          kend = a.EndDate,
                          b.TeamId,
                      }).ToList();
            foreach (var item in plan.teams)
            {
                cd.count+= cc.Where(x=> plan.plan.StartDate >= x.kstr && plan.plan.EndDate <= x.kend&& x.TeamId==item.TeamId).Count();

                cd.teamnames +=item.TeamName+"\n";
            }
            if(cd.count>0)
            {
                cd.count = 0;
                cd.teamnames = cd.teamnames.TrimEnd('\n');
                return cd;// 已有冲突
            }
            cd.teamnames = "";
            cal_plan cplan = new cal_plan
                {
                    ChangeShiftType = plan.plan.ChangeShiftType,
                    CreateDate = plan.plan.CreateDate,
                    Creator = plan.plan.Creator,
                    CreateID = plan.plan.CreateID,
                    EndDate = plan.plan.EndDate,
                    Modifier = plan.plan.Modifier,
                    ModifyDate = plan.plan.ModifyDate,
                    PlanCode = plan.plan.PlanCode,
                    PlanName = plan.plan.PlanName,
                    TeamType = plan.plan.TeamType,
                    Status = plan.plan.Status,
                    StartDate = plan.plan.StartDate,
                    ModifyID = plan.plan.ModifyID,
                    PlanId = plan.plan.PlanId,
                    Remark = plan.plan.Remark,
                    ShiftType = plan.plan.ShiftType
                };
            cplan.PlanId = Guid.NewGuid();
            if (string.IsNullOrEmpty(cplan.PlanCode))
            {
                cplan.PlanCode = Guid.NewGuid().ToString();
            }
            _repository.Add(cplan);
            _repository.SaveChanges();
            
            List<cal_planshift> shifts = new List<cal_planshift>();
            foreach (var item in plan.bcdto)
            {
                cal_planshift shift = new cal_planshift
                {
                    PlanShiftId = Guid.NewGuid().ToString(),
                    PlanId = cplan.PlanId.ToString(),
                    PlanShiftName = item.BName,
                    Sequence = "",
                    StartTime = item.BStrart,
                    EndTime = item.BEnd
                };
                shifts.Add(shift);
            }

            _planshiftrepository.AddRange(shifts);
            _planshiftrepository.SaveChanges();


            List<cal_planteam> teams = new List<cal_planteam>();
            int i = 0;
            foreach (team item in plan.teams)
            {
                cal_planteam team = new cal_planteam
                {
                    TeamId = item.TeamId,
                    PlanId = cplan.PlanId,
                    PlanTeamId = Guid.NewGuid(),
                    TeamName = item.TeamName,
                    Sequence = i,
                    TeamCode = item.TeamCode
                };
                i++;
                teams.Add(team);
            }


            _plantemerepository.AddRange(teams);
            cd.count = _plantemerepository.SaveChanges();
            return cd;
        }   
        public Addplanresultdto UpdatePlan(PlanDto plan)
        {

            Addplanresultdto cd = new Addplanresultdto();
            cd.count = 0;
            cd.teamnames = "";


            foreach (var item in plan.teams)
            {
                //写逻辑
                cd.count += (from a in _repository.Find(x => plan.plan.StartDate >= x.StartDate && plan.plan.EndDate <= x.EndDate)
                             join
                          b in _plantemerepository.Find(x => item.TeamId == x.TeamId) on a.PlanId equals b.PlanId
                             select a).Count();
                cd.teamnames += item.TeamName + "\n";

            }
            if (cd.count > 0)
            {
                cd.teamnames = cd.teamnames.TrimEnd('\n');
                return cd;// 已有冲突
            }
            cd.teamnames = "";
            //先删除
            _repository.Delete(x => x.PlanId == plan.plan.PlanId);
            cal_plan cplan = new cal_plan
            {
                ChangeShiftType = plan.plan.ChangeShiftType,
                CreateDate = plan.plan.CreateDate,
                Creator = plan.plan.Creator,
                CreateID = plan.plan.CreateID,
                EndDate = plan.plan.EndDate,
                Modifier = plan.plan.Modifier,
                ModifyDate = plan.plan.ModifyDate,
                PlanCode = plan.plan.PlanCode,
                PlanName = plan.plan.PlanName,
                TeamType = plan.plan.TeamType,
                Status = plan.plan.Status,
                StartDate = plan.plan.StartDate,
                ModifyID = plan.plan.ModifyID,
                PlanId = plan.plan.PlanId,
                Remark = plan.plan.Remark,
                ShiftType = plan.plan.ShiftType
            };
            _repository.Add(cplan);
            _repository.SaveChanges();

            _planshiftrepository.Delete(x => x.PlanId == plan.plan.PlanId.ToString());
            List<cal_planshift> shifts = new List<cal_planshift>();
            foreach (var item in plan.bcdto)
            {
                cal_planshift shift = new cal_planshift
                {
                    PlanShiftId = Guid.NewGuid().ToString(),
                    PlanId = cplan.PlanId.ToString(),
                    PlanShiftName = item.BName,
                    Sequence = "",
                    StartTime = item.BStrart,
                    EndTime = item.BEnd
                };
                shifts.Add(shift);
            }

            _planshiftrepository.AddRange(shifts);
            _planshiftrepository.SaveChanges();

            _plantemerepository.Delete(x => x.PlanId == plan.plan.PlanId);
            List<cal_planteam> teams = new List<cal_planteam>();
            int i = 0;
            foreach (team item in plan.teams)
            {
                cal_planteam team = new cal_planteam
                {
                    TeamId = item.TeamId,
                    PlanId = cplan.PlanId,
                    PlanTeamId = Guid.NewGuid(),
                    TeamName = item.TeamName,
                    Sequence = i,
                    TeamCode = item.TeamCode
                };
                i++;
                teams.Add(team);
            }


            cd.count = _plantemerepository.SaveChanges();
            return cd;
        }
        public List<team> GetBanzu(string palanId)
        {
            List<team> teams = (from a in _plantemerepository.FindAsIQueryable(x => x.PlanId.ToString() == palanId)
                                join b in _temerepository.FindAsIQueryable(x => 1 == 1)
                                on a.TeamId equals b.TeamId
                                select new team
                                {
                                    cal_teammember = null,
                                    CreateDate = b.CreateDate,
                                    Creator = b.Creator,
                                    CreateID = b.CreateID,
                                    elementIndex = 0,
                                    Modifier = b.Modifier,
                                    ModifyDate = b.ModifyDate,
                                    ModifyID = b.ModifyID,
                                    Remark = b.Remark,
                                    TeamCode = b.TeamCode,
                                    TeamId = b.TeamId,
                                    TeamName = b.TeamName,
                                    TeamType = b.TeamType,

                                }).ToList();
            return teams;
        }
        public int DeletePlan(List<string> ids)
        {
            _planshiftrepository.Delete(x => ids.Contains(x.PlanId));
            _planshiftrepository.SaveChanges();
            _plantemerepository.Delete(x => ids.Contains(x.PlanId.ToString()));
            return _plantemerepository.SaveChanges();
        }


    }
}
